package cn.sc.summer.constant.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.sc.summer.constant.service.Support;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 类名：spring自定义工具类
 *
 * @author a-xin
 * @date 2023/9/28 11:33
 */
public final class SpringUtilX {

    /**
     * 获取执行bean类型
     *
     * @param clazz          指定bean类型
     * @param support        需要的类型
     * @param defaultSupport 默认类型
     * @param <T>            类型，继承support接口
     * @return 如果存在则返回，不存在则返回默认类型bean
     */
    public static <T extends Support> T getSupportBean(Class<T> clazz, String support, T defaultSupport) {
        Map<String, T> beansOfType = SpringUtil.getBeansOfType(clazz);
        if (CollUtil.isEmpty(beansOfType)) {
            return defaultSupport;
        }
        List<T> beans = new ArrayList<>();
        beansOfType.forEach((key, bean) -> beans.add(bean));
        for (T bean : beans) {
            if (bean.checkSupports(support)) {
                return bean;
            }
        }
        return defaultSupport;
    }

    /**
     * 获取执行bean类型
     *
     * @param clazz          指定bean类型
     * @param support        需要的类型
     * @param defaultSupport 默认类型
     * @param <T>            类型，继承support接口
     * @return 如果存在则返回，不存在则返回默认类型bean
     */
    public static <T extends Support> T getSupportBean(Class<T> clazz, String support, String defaultSupport) {
        Map<String, T> beansOfType = SpringUtil.getBeansOfType(clazz);
        if (CollUtil.isEmpty(beansOfType)) {
            throw new IllegalArgumentException("There is no corresponding bean information!");
        }
        List<T> beans = new ArrayList<>();
        beansOfType.forEach((key, bean) -> beans.add(bean));
        for (T bean : beans) {
            if (bean.checkSupports(support)) {
                return bean;
            }
        }
        for (T bean : beans) {
            if (bean.checkSupports(defaultSupport)) {
                return bean;
            }
        }
        throw new IllegalArgumentException("There is no corresponding bean information: " + defaultSupport);
    }

}

